﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace STSdb.MTL
{
    public class TablesCompactorHeader
    {
        /// <summary>
        /// Maximum size of the information about compacting file
        /// </summary>
        public static int _CompactorHeaderSize = 64*4;

        public TablesCompactorHeader()
        {
            CompactionIsStarted = false;
            //////////////////////////////////////////////
            PositionOfCompactionElement = (uint)_CompactorHeaderSize;

            OriginalUserTableName = String.Empty;
        }

        /// <summary>
        /// 
        /// </summary>
        public bool CompactionIsStarted { get; set; }


        /// <summary>
        /// 
        /// </summary>
        public ulong PositionOfCompactionElement { get; set; }

        public string OriginalUserTableName { get; set; }
        

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pos"></param>
        /// <param name="started"></param>
        /// <returns></returns>
        public static byte[] GetCompactorHeaderAsByteArray(TablesCompactorHeader tch)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append((tch.CompactionIsStarted) ? "1" : "0");  //if compaction procedure was started or stopped
            sb.Append(";");
            sb.Append(tch.PositionOfCompactionElement.ToString());  //last compaction reference
            sb.Append(";");
            sb.Append(System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(tch.OriginalUserTableName))); //Original user table name
            sb.Append(";");

            byte[] rbt = new byte[_CompactorHeaderSize];
            int i = 0;
            foreach (byte bt in System.Text.Encoding.UTF8.GetBytes(sb.ToString()))
            {
                rbt[i] = bt;
                i++;
            }

            return rbt;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="bt"></param>
        /// <returns></returns>
        public static TablesCompactorHeader GetCompactorHeaderFromByteArray(byte[] bt)
        {
            TablesCompactorHeader tch = new TablesCompactorHeader();

            string[] el = System.Text.Encoding.UTF8.GetString(bt).Split(new string[] { ";" }, StringSplitOptions.None);

            tch.CompactionIsStarted = Convert.ToBoolean(Convert.ToInt32(el[0]));
            tch.PositionOfCompactionElement = Convert.ToUInt64(el[1]);
            tch.OriginalUserTableName = System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(el[2]));

            return tch;
        }
    }
}
